package com.gilight.base.mq.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gilight.base.base.exception.AppServiceException;
import com.gilight.base.base.exception.ExceptionDefinition;
import com.gilight.base.component.CacheComponent;
import com.gilight.base.component.CacheConst;
import com.gilight.base.component.LockComponent;
import com.gilight.base.component.LockConst;
import com.gilight.base.dto.order.OrderRequestSkuDTO;
import com.gilight.base.enums.DMQHandlerType;
import com.gilight.base.enums.OrderStatusType;
import com.gilight.base.mapper.OrderSkuMapper;
import com.gilight.base.mapper.SkuMapper;
import com.gilight.base.model.SkuStockInfoModel;
import com.gilight.base.model.order.OrderDO;
import com.gilight.base.model.order.OrderSkuDO;
import com.gilight.base.service.order.OrderBizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class OrderAutoCancelHandler implements RedisNotifyHandler {

    private static final Logger logger = LoggerFactory.getLogger(OrderAutoCancelHandler.class);

    @Autowired
    private LockComponent lockComponent;

    @Autowired
    private OrderBizService orderBizService;

    @Autowired
    private OrderSkuMapper orderSkuMapper;

    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private CacheComponent cacheComponent;

    /**
     * @param orderNo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int handle(String orderNo) {
        try {
            OrderDO orderDO = orderBizService.checkOrderExistByNo(orderNo, null).get(0);
            if (orderDO.getStatus() != OrderStatusType.UNPAY.getCode()) {
                throw new AppServiceException(ExceptionDefinition.ORDER_STATUS_NOT_SUPPORT_CANCEL);
            }
            OrderDO updateOrderDO = new OrderDO();
            updateOrderDO.setStatus(OrderStatusType.CANCELED_SYS.getCode());
            updateOrderDO.setGmtUpdate(new Date());
            List<OrderSkuDO> orderSkuList = orderSkuMapper.selectList(new QueryWrapper<OrderSkuDO>().eq("order_id", orderDO.getId()));
            orderSkuList.forEach(item -> {
                skuMapper.returnSkuStock(item.getSkuId(), item.getNum());
            });
            //恢复库存
            orderBizService.changeOrderSubStatus(orderNo, OrderStatusType.UNPAY.getCode(), updateOrderDO);
            this.reCalcSpuStock(orderSkuList);
            //返还用户优惠卷
            Long couponId = orderDO.getCouponId();
            if(couponId != null){  //如果该订单中使用了优惠卷那么将优惠郑返回到用户账号
                orderBizService.backCouponToUser(couponId,orderDO.getUserId(),orderDO.getId());
            }
            logger.info("[订单自动取消] 订单号：" + orderNo);
        } catch (Exception e) {
            logger.error("[订单自动取消任务] 异常", e);
            return 0;
        } finally {
            lockComponent.release(LockConst.ORDER_SUB_STATUS_LOCK + orderNo);
        }
        return 1;
    }

    @Override
    public int getCode() {
        return DMQHandlerType.ORDER_AUTO_CANCEL.getCode();
    }

    public void reCalcSpuStock(List<OrderSkuDO> orderSkuList){
        Map<Long, List<OrderSkuDO>> goupBySpuid = orderSkuList.stream().collect(Collectors.groupingBy(OrderSkuDO::getSpuId));
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                goupBySpuid.forEach((k,v)->{
                    int sum = 0;
                    for(int i= 0;i<v.size();i++){
                        OrderSkuDO orderRequestSkuDTO = v.get(i);
                        sum+=orderRequestSkuDTO.getNum();
                    }
                    if(cacheComponent.getHashObj(CacheConst.PRT_SPU_STOCK_BUCKET, "C" + k,Object.class)==null){
                        return;
                    }
                    long surplus = cacheComponent.incrementHashKey(CacheConst.PRT_SPU_STOCK_BUCKET, "C" + k, sum);
                });
            }
        });
    }
}
